'''
Author: GlenZhao
Date: 2025-05-07 10:51:47
LastEditors: GlenZhao
LastEditTime: 2025-05-09 18:38:45
Description: 
'''
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from core.database import db_getter
from apps.auth.menu.crud import MenuDal
from apps.auth.user.utils.auth import Auth, UserAuth
from utils.response import SuccessResponse
from .schemas import Menu, Meta, RouterOut, SubMenuOut
from .models import AuthMenu

app = APIRouter()

@app.get("/menus", summary="菜单")
async def get_menus(
    db: AsyncSession = Depends(db_getter)
):
    data: list[AuthMenu] = await MenuDal(db).get_datas(limit=0, v_order_field="order", v_return_objs=True, v_return_count=False)

    res = {}
    rank = 1
    for d in data:
        item = Menu.model_validate(d)
        meta = Meta.model_validate(item).model_dump(exclude_none=True)
        if item.parent_id:
            if item.parent_id not in res:
                res[item.parent_id] = {
                    "children": []
                }
            elif "children" not in res[item.parent_id]:
                res[item.parent_id]["children"] = []
            sub_menu = SubMenuOut(
                name = item.name,
                title = item.title,
                path = item.path,
                component = item.component,
                meta = meta
            )
            res[item.parent_id]["children"].append(sub_menu.model_dump(exclude_none=True))
        else:
            menu = RouterOut(
                name=item.name,
                rank=rank,
                title = item.title,
                path = item.path,
                component = item.component,
                order = item.order,
                redirect = item.redirect,
                meta = meta
            )
            if item.id not in res:
                res[item.id] = {}
            res[item.id].update(menu.model_dump(exclude_none=True))
            rank += 1

    return SuccessResponse(list(res.values()))